<template>
  <div style="width: 70%;background-color: white;margin: 0px auto;padding: 20px;">
      <router-link style="position: fixed;top:10px;left: 10px;" to="/main/biao" class="back-btn">
        <button>返回</button>
      </router-link>
    <div class="button-group">
      <button v-if="!isViewMode" @click="saveData">保存</button>
      <button @click="downloadPdf">下载 PDF</button>
      <button @click="goToList">列表</button>
      <button v-if="isViewMode" @click="handleEdit">编辑</button>
    </div>
    <div class="container" id="content">
      <h2 style="font-size: 1.2em;">员工入职资料表</h2>
      <span style="float: left;margin-bottom: 10px;">
        申请职位：
        <input type="text" id="name" class="underline-input" v-model="entr.applicationPosition"
          :disabled="isViewMode" />
      </span>
      <span class="right-float">
        申请日期：
        <input type="text" class="underline-input1" v-model="entr.applicationYear" :disabled="isViewMode" />年
        <input type="text" class="underline-input1" v-model="entr.applicationMonth" :disabled="isViewMode" />月
        <input type="text" class="underline-input1" v-model="entr.applicationDay" :disabled="isViewMode" />日
      </span>
      <form style="margin-top: 5px;">
        <table>
          <tbody>
            <tr>
              <td colspan="10" style="text-align: left">一、个人基本资料</td>
            </tr>
            <tr>
              <td colspan="1">姓名</td>
              <td colspan="2"><input v-model="entr.name" :disabled="isViewMode"></td>
              <td colspan="1">性别</td>
              <td colspan="1"><input v-model="entr.gender" :disabled="isViewMode"></td>
              <td colspan="1">出生年月</td>
              <td colspan="2"><input v-model="entr.birth" :disabled="isViewMode"></td>
              <td rowspan="8" colspan="2" class="img">
                <span style="float: inline-end" id="uploadSpan"
                  :style="{ display: !isViewMode && uploadSpanDisplay ? 'block' : 'none' }">
                  照片
                  <input title="图片" type="file" id="imageUpload" accept="image/*" @change="handleImageUpload"
                    :disabled="isViewMode" />
                </span>
                <span id="previewSpan" :style="{ display: previewSpanDisplay }">
                  <img style="height: 49mm; width: 35mm;border: 0px;object-fit: cover;" id="preview"
                    :src="previewImageSrc" alt="预览图片" />
                  <button id="deleteBtn" v-if="!isViewMode" @click="deleteImage">删除</button>
                </span>
              </td>
            </tr>
            <tr>
              <td>籍贯</td>
              <td><input v-model="entr.hometown" :disabled="isViewMode"></td>
              <td>身高</td>
              <td><input style="width: 55%;" v-model="entr.height" :disabled="isViewMode">cm</td>
              <td colspan="2">文化程度</td>
              <td colspan="2"><input v-model="entr.educationLevel" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td>专业</td>
              <td colspan="2"><input v-model="entr.major" :disabled="isViewMode"></td>
              <td colspan="2">毕业学校</td>
              <td colspan="3"><input v-model="entr.graduationSchool" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td>婚否</td>
              <td><input v-model="entr.married" :disabled="isViewMode"></td>
              <td>健康状况</td>
              <td><input v-model="entr.healthCondition" :disabled="isViewMode"></td>
              <td>语言能力</td>
              <td colspan="3">
                语种:<span><input style="width: 50px;height: 20px;" v-model="entr.language" :disabled="isViewMode"></span>
                （
                <span><input style="width: 20px;height: 20px;" v-model="entr.languageLevel"
                    :disabled="isViewMode"></span> ）级
              </td>
            </tr>
            <tr>
              <td colspan="3">其他技能或持有专业证照</td>
              <td colspan="2"><input v-model="entr.otherSkills" :disabled="isViewMode"></td>
              <td>特长</td>
              <td colspan="2"><input v-model="entr.specialty" :disabled="isViewMode"></td>
            </tr>
            <tr></tr>
            <tr>
              <td colspan="2">现住地址</td>
              <td colspan="3"><input v-model="entr.currentAddress" :disabled="isViewMode"></td>
              <td>联系电话</td>
              <td colspan="2"><input v-model="entr.contactPhone" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="2">职位信息来源</td>
              <td colspan="2"><input v-model="entr.jobInfoSource" :disabled="isViewMode"></td>
              <td>期望薪酬</td>
              <td><input v-model="entr.expectedSalary" :disabled="isViewMode"></td>
              <td>最快到职日期</td>
              <td><input v-model="entr.earliestStart" :disabled="isViewMode"></td>
            </tr>
            <tr></tr>
            <tr>
              <td rowspan="2" colspan="2">紧急联系人</td>
              <td colspan="3">姓名（尽量为直系亲属）</td>
              <td colspan="2"><input v-model="entr.emergencyContactName" :disabled="isViewMode"></td>
              <td>关系</td>
              <td colspan="2"><input v-model="entr.emergencyContactRelation" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="2">通讯地址</td>
              <td colspan="3"><input v-model="entr.emergencyContactAddress" :disabled="isViewMode"></td>
              <td>电话</td>
              <td colspan="2"><input v-model="entr.emergencyContactPhone" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="10" style="text-align: left">
                二、受教育程度或培训经历
              </td>
            </tr>
            <tr>
              <th colspan="2">学校名称</th>
              <th>专业</th>
              <th>学历</th>
              <th>入学年月</th>
              <th>离校年月</th>
              <th>毕业或结业</th>
              <th>有否证件</th>
              <th colspan="2">备注</th>
            </tr>
            <tr>
              <td colspan="2"><input v-model="entr.schoolName" :disabled="isViewMode"></td>
              <td><input v-model="entr.schoolMajor" :disabled="isViewMode"></td>
              <td><input v-model="entr.schoolEducation" :disabled="isViewMode"></td>
              <td><input v-model="entr.admission" :disabled="isViewMode"></td>
              <td><input v-model="entr.graduation" :disabled="isViewMode"></td>
              <td><input v-model="entr.graduationStatus" :disabled="isViewMode"></td>
              <td><input v-model="entr.hasCertificate" :disabled="isViewMode"></td>
              <td colspan="2"><input v-model="entr.schoolNote" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="2">{{ entr.schoolName2 }}</td>
              <td>{{ entr.schoolMajor2 }}</td>
              <td>{{ entr.schoolEducation2 }}</td>
              <td>{{ entr.admission2 }}</td>
              <td>{{ entr.graduation2 }}</td>
              <td><input v-model="entr.graduationStatus2" :disabled="isViewMode"></td>
              <td><input v-model="entr.hasCertificate2" :disabled="isViewMode"></td>
              <td colspan="2">{{ entr.schoolNote2 }}</td>
            </tr>
            <tr>
              <td colspan="2">{{ entr.schoolName3 }}</td>
              <td>{{ entr.schoolMajor3 }}</td>
              <td>{{ entr.schoolEducation3 }}</td>
              <td>{{ entr.admission3 }}</td>
              <td>{{ entr.graduation3 }}</td>
              <td><input v-model="entr.graduationStatus3" :disabled="isViewMode"></td>
              <td><input v-model="entr.hasCertificate3" :disabled="isViewMode"></td>
              <td colspan="2">{{ entr.schoolNote3 }}</td>
            </tr>
            <tr>
              <td colspan="10" style="text-align: left">三、工作经历</td>
            </tr>
            <tr>
              <th colspan="2">单位名称</th>
              <th>到职年月</th>
              <th>离职年月</th>
              <th>工作职务</th>
              <th>底薪</th>
              <th>直系主管</th>
              <th>离职原因</th>
              <th colspan="2">查询电话</th>
            </tr>
            <tr>
              <td colspan="2"><input v-model="entr.companyName" :disabled="isViewMode"></td>
              <td><input v-model="entr.join" :disabled="isViewMode"></td>
              <td><input v-model="entr.leave" :disabled="isViewMode"></td>
              <td><input v-model="entr.jobTitle" :disabled="isViewMode"></td>
              <td><input v-model="entr.baseSalary" :disabled="isViewMode"></td>
              <td><input v-model="entr.directSupervisor" :disabled="isViewMode"></td>
              <td>{{ entr.leaveReason }}</td>
              <td colspan="2"><input v-model="entr.inquiryPhone" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="2"><input v-model="entr.companyName2" :disabled="isViewMode"></td>
              <td><input v-model="entr.join2" :disabled="isViewMode"></td>
              <td><input v-model="entr.leave2" :disabled="isViewMode"></td>
              <td><input v-model="entr.jobTitle2" :disabled="isViewMode"></td>
              <td><input v-model="entr.baseSalary2" :disabled="isViewMode"></td>
              <td><input v-model="entr.directSupervisor2" :disabled="isViewMode"></td>
              <td>{{ entr.leaveReason2 }}</td>
              <td colspan="2"><input v-model="entr.inquiryPhone2" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="2"><input v-model="entr.companyName3" :disabled="isViewMode"></td>
              <td><input v-model="entr.join3" :disabled="isViewMode"></td>
              <td><input v-model="entr.leave3" :disabled="isViewMode"></td>
              <td><input v-model="entr.jobTitle3" :disabled="isViewMode"></td>
              <td><input v-model="entr.baseSalary3" :disabled="isViewMode"></td>
              <td><input v-model="entr.directSupervisor3" :disabled="isViewMode"></td>
              <td>{{ entr.leaveReason3 }}</td>
              <td colspan="2"><input v-model="entr.inquiryPhone3" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="2"><input type="text" v-model="entr.companyName4" :disabled="isViewMode"></td>
              <td><input v-model="entr.join4" :disabled="isViewMode"></td>
              <td><input v-model="entr.leave4" :disabled="isViewMode"></td>
              <td><input v-model="entr.jobTitle4" :disabled="isViewMode"></td>
              <td><input v-model="entr.baseSalary4" :disabled="isViewMode"></td>
              <td><input v-model="entr.directSupervisor4" :disabled="isViewMode"></td>
              <td>{{ entr.leaveReason4 }}</td>
              <td colspan="2"><input v-model="entr.inquiryPhone4" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td colspan="10">
                <span class="left-float">
                  详述工作经验（请说明在以往的工作中主要负责和熟悉的部分，并取得了哪些成就）：
                </span>
                <textarea spellcheck="false" id="workExperience" placeholder="" style="width: 100%; height: 100px"
                  v-model="entr.workExperienceDetail" :disabled="isViewMode"></textarea>
              </td>
            </tr>
            <tr>
              <td colspan="10" style="text-align: left">四、家庭成员</td>
            </tr>
            <tr>
              <th>姓名</th>
              <th>称谓</th>
              <th>年龄</th>
              <th colspan="3">任职机构或详细地址</th>
              <th>职称</th>
              <th colspan="3">联络电话</th>
            </tr>
            <tr>
              <td><input v-model="entr.familyName" :disabled="isViewMode"></td>
              <td><input v-model="entr.familyRelation" :disabled="isViewMode"></td>
              <td><input type="text" style="width: 50px" v-model="entr.familyAge" :disabled="isViewMode"></td>
              <td colspan="3">{{ entr.familyAddress }}</td>
              <td><input v-model="entr.familyTitle" :disabled="isViewMode"></td>
              <td colspan="3"><input v-model="entr.familyPhone" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td><input v-model="entr.familyName2" :disabled="isViewMode"></td>
              <td><input v-model="entr.familyRelation2" :disabled="isViewMode"></td>
              <td><input type="text" style="width: 50px" v-model="entr.familyAge2" :disabled="isViewMode"></td>
              <td colspan="3">{{ entr.familyAddress2 }}</td>
              <td><input v-model="entr.familyTitle2" :disabled="isViewMode"></td>
              <td colspan="3"><input v-model="entr.familyPhone2" :disabled="isViewMode"></td>
            </tr>
            <tr>
              <td style="border: 0px">声明：</td>
              <td colspan="9" style="border: 0px; text-align: left">
                1、申请人承诺未隐瞒任何身体疾病，否则由此造成的一切后果由申请人自行承担，申请人隐瞒的疾病导致其不能胜任申请职位的，公司有权终止劳动合同并无需支付任何经济补偿金或赔偿金。
              </td>
            </tr>
            <tr>
              <td style="border: 0px"></td>
              <td colspan="9" style="border: 0px; text-align: left">
                2、本人慎重申明以上所填各项及所持证件均属实，如有虚伪记载，愿受开除处分。
              </td>
            </tr>
          </tbody>
        </table>
        <p style="display: flex;align-items: center;margin: 0px;">
          申请人签名：
          <img :src="entr.signature" alt="签名" style="width: 100px; height: 50px; border: 0px; " />
          <span class="right-float">
            日期:
            <input type="text" class="underline-input1" v-model="entr.signYear" :disabled="isViewMode" />年
            <input type="text" class="underline-input1" v-model="entr.signMonth" :disabled="isViewMode" />月
            <input type="text" class="underline-input1" v-model="entr.signDay" :disabled="isViewMode" />日
          </span>
        </p>
      </form>
    </div>
  </div>
</template>

<script>
import html2pdf from "html2pdf.js";
import request from '@/utils/request';

export default {
  name: "entryTable",
  data() {
    return {
      previewImageSrc: "",
      uploadSpanDisplay: "block",
      previewSpanDisplay: "none",
      entr: {},
      isViewMode: false,
    };
  },
  created() {
    console.log('组件创建，完整路由信息:', this.$route);
    console.log('Route query:', this.$route.query);
    const id = this.$route.query.id;
    const mode = this.$route.query.mode;

    // 明确设置查看模式
    this.isViewMode = mode === 'view';
    console.log('当前模式:', this.isViewMode ? '查看模式' : '编辑模式');

    if (id) {
      console.log('开始获取数据...');
      this.fetchEmployeeData(id);
    } else {
      console.log('没有获取到ID，可能是新建模式');
      this.isViewMode = false;
    }
  },
  methods: {
    async fetchEmployeeData(id) {
      try {
        console.log('Fetching data for ID:', id);
        const response = await request.get('/api/entry/view/' + id);
        console.log('API Response:', response);

        if (response.data) {
          this.entr = response.data;

          // 如果有图片，显示图片
          if (this.entr.imageUrl) {
            this.previewImageSrc = this.entr.imageUrl;
            this.uploadSpanDisplay = 'none';
            this.previewSpanDisplay = 'block';
          }
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        alert('获取数据失败: ' + (error.response?.data?.message || error.message));
      }
    },
    handleImageUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewImageSrc = e.target.result;
          this.uploadSpanDisplay = "none";
          this.previewSpanDisplay = "block";
        };
        reader.readAsDataURL(file);
      }
    },
    deleteImage() {
      const imageUpload = document.getElementById("imageUpload");
      imageUpload.value = "";
      this.previewImageSrc = "";
      this.uploadSpanDisplay = "block";
      this.previewSpanDisplay = "none";
    },
    downloadPdf() {
      const element = document.getElementById("content");
      const opt = {
        margin: 10, // 适当增加边距
        filename: "员工入职资料表.pdf",
        image: { type: "", quality: 0.98 },
        html2canvas: { scale: 1 }, // 调整缩放比例
        jsPDF: { unit: "mm", format: "A4", orientation: "portrait" }, // 设置为 A4 格式
      };
      html2pdf().from(element).set(opt).save();
    },
    goToList() {
      this.$router.push('/main/biao/rzziliao-list');
    },
    async saveData() {
      try {
        const formData = {
          id: this.$route.query.id || '',
          applicationPosition: this.entr.applicationPosition || '',
          applicationYear: this.entr.applicationYear || '',
          applicationMonth: this.entr.applicationMonth || '',
          applicationDay: this.entr.applicationDay || '',
          name: this.entr.name || '',
          gender: this.entr.gender || '',
          birth: this.entr.birth || '',
          hometown: this.entr.hometown || '',
          height: this.entr.height || '',
          educationLevel: this.entr.educationLevel || '',
          major: this.entr.major || '',
          graduationSchool: this.entr.graduationSchool || '',
          married: this.entr.married || '',
          healthCondition: this.entr.healthCondition || '',
          language: this.entr.language || '',
          languageLevel: this.entr.languageLevel || '',
          otherSkills: this.entr.otherSkills || '',
          specialty: this.entr.specialty || '',
          currentAddress: this.entr.currentAddress || '',
          contactPhone: this.entr.contactPhone || '',
          jobInfoSource: this.entr.jobInfoSource || '',
          expectedSalary: this.entr.expectedSalary || '',
          earliestStart: this.entr.earliestStart || '',
          emergencyContactName: this.entr.emergencyContactName || '',
          emergencyContactRelation: this.entr.emergencyContactRelation || '',
          emergencyContactAddress: this.entr.emergencyContactAddress || '',
          emergencyContactPhone: this.entr.emergencyContactPhone || '',
          schoolName: this.entr.schoolName || '',
          schoolMajor: this.entr.schoolMajor || '',
          schoolEducation: this.entr.schoolEducation || '',
          admission: this.entr.admission || '',
          graduation: this.entr.graduation || '',
          graduationStatus: this.entr.graduationStatus || '',
          hasCertificate: this.entr.hasCertificate || '',
          schoolNote: this.entr.schoolNote || '',
          companyName: this.entr.companyName || '',
          join: this.entr.join || '',
          leave: this.entr.leave || '',
          jobTitle: this.entr.jobTitle || '',
          baseSalary: this.entr.baseSalary || '',
          directSupervisor: this.entr.directSupervisor || '',
          leaveReason: this.entr.leaveReason || '',
          inquiryPhone: this.entr.inquiryPhone || '',
          workExperienceDetail: this.entr.workExperienceDetail || '',
          signature: this.entr.signature || '',
          signYear: this.entr.signYear || '',
          signMonth: this.entr.signMonth || '',
          signDay: this.entr.signDay || '',
          imageUrl: this.previewImageSrc || '',  // 确保imageUrl字段有默认值
        };

        console.log('发送的数据:', formData);

        try {
          const response = await request.post('/api/entry/save', formData);
          console.log('收到响应:', response);

          if (response.data) {
            alert('保存成功！');
            this.$router.push('/main/biao/rzziliao-list');
          } else {
            alert('保存失败，请重试');
          }
        } catch (networkError) {
          console.error('网络错误:', networkError);
          alert('无法连接到服务器，请检查网络连接或联系管理员');
        }
      } catch (error) {
        console.error('保存失败:', error);
        alert('保存失败: ' + error.message);
      }
    },
    handleEdit() {
      const id = this.$route.query.id;
      // 跳转到编辑模式
      this.$router.push({
        path: '/main/biao/rzziliao',
        query: { id: id, mode: 'edit' }
      }).then(() => {
        // 路由跳转后更新模式
        this.isViewMode = false;
        // 重新获取数据
        this.fetchEmployeeData(id);
      });
    },
  },
};
</script>
<style scoped>
body {
  font-family: "宋体";
  font-size: 13px !important;
  margin: 0;
  padding: 0;
}

table {
  border-collapse: collapse;
  table-layout: fixed;
  width: 100%;
}

td,
th {
  border: 1px solid #000;
  text-align: center;
  width: 100px;
  outline: none;
  height: 25px;
  padding: 0px;
}

h2 {
  padding-left: 260px;
  margin-top: 0px;
}

.underline-input {
  border: none;
  border-bottom: 1px solid #000;
  width: 200px;
  font-size: 13px;
  outline: none;
  background: transparent;
  text-align: center;
}

.underline-input1 {
  border: none;
  border-bottom: 1px solid #000;
  width: 40px;
  font-size: 13px;
  outline: none;
  background: transparent;
  text-align: center;
}

input {
  width: 87%;
  height: 75%;
  outline: none;
  border: 0px;
  text-align: center;
  background-color: transparent;
  font-family: "宋体";
  color: #000000;
  font-size: 13px;
}

.no {
  border: none;
}

#preview {
  width: 300px;
  height: auto;
  border: 1px solid #ccc;
}

#previewSpan {
  position: relative;
  /* display: none; */
}

#deleteBtn {
  display: none;
  position: absolute;
  top: -170px;
  right: 5px;
  background-color: #cdcdcd;
  color: #000000;
  border: none;
  padding: 5px;
  cursor: pointer;
  border-radius: 5px;
}

#previewSpan:hover #deleteBtn {
  display: block;
}

.left-float {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.right-float {
  position: absolute;
  left: 420px;
}

#workExperience {
  outline: none;
  width: 100%;
  height: 100px;
  padding: 5px;
  box-sizing: border-box;
  resize: none;
  border: 0px;
  font-size: 14px;
  background-color: transparent;
  color: #000000;
}

::placeholder {
  color: black;
}

@media print {
  table {
    width: 100%;
  }

  td,
  th {
    width: auto;
  }

  input {
    width: 90%;
  }

  /* 设置页面边距 */
  @page {
    margin: 10mm;
    size: A4 portrait;
  }

  /* 调整页面布局 */
  body {
    font-size: 12pt !important;
  }

  table {
    width: 90%;
    border-collapse: collapse;
    page-break-inside: avoid;
  }

  td,
  th {
    border: 1px solid #000;
    padding: 5px;
  }

  .container {
    width: 100%;
    margin: 0;
    box-sizing: border-box;
  }

  /* 调整图片大小 */
  img {
    max-width: 100%;
    height: auto;
  }

  /* 强制分页
      .page-break {
        page-break-after: always;
      } */
}
</style>